/**
 *  地质模型操作类
 *  作者：adams
 */
import * as mars3d from "mars3d";
import * as Cesium from "mars3d-cesium";
import GeologicalModel from "@/plugins/te/GeologicalModel";
import $modal from "@/plugins/modal";
import { cloneDeep } from "lodash";
import * as drillApi from "@/plugins/te/api/drill";
import useReservesStore from "@/store/modules/reserves";

class modelEditor {
  mapInstance;
  // 地址模型编辑实例
  gmodel;
  viewer;
  pointPrimitiveArray = [];
  pointCoordinationArray = [];
  labelEntities = [];
  pointCollection;
  polygonPrimitive = undefined;
  mid = 1223;
  spaceID = 200;
  section = undefined;
  drill;
  handler;
  labelRawMatrices = [];
  labelLayerIds = [];
  showMark = false;
  showPickInfo = false;
  graphicLayer;
  liftUpVal = 0;
  // 单个地层选中
  selectedLayerEnabled = false;
  // 图层是否选中
  layerSelectedFlag = false;
  layersOptions = [
    {
      position: [117.319458, 30.247167, 242.3],
      textContent: "Ⅲ熔剂用白云岩",
      reserves: "8254.35万吨",
      index: 27,
    },
    {
      position: [117.317902, 30.24576, 218.6],

      textContent: "Ⅰ电石用灰岩",
      reserves: "6115.96万吨",
      index: 18,
    },
    {
      position: [117.314976, 30.244493, 207.6],
      textContent: "3建筑用灰岩",
      reserves: "2666.82万吨",
      index: 13,
    },
    {
      position: [117.319679, 30.243986, 218.9],
      textContent: "B2熔剂用白云岩",
      reserves: "1273.59万吨",
      index: 12,
    },
    {
      position: [117.316185, 30.243563, 217.3],
      textContent: "4建筑用灰岩",
      reserves: "1569.53万吨",
      index: 11,
    },
    {
      position: [117.317837, 30.243565, 222.8],
      textContent: "B3熔剂用白云岩",
      reserves: "807.70万吨",
      index: 10,
    },
    {
      position: [117.315752, 30.242557, 206.5],
      textContent: "Ⅱ电石用灰岩",
      reserves: "3976.33万吨",
      index: 4,
    },
    {
      position: [117.318002, 30.24225, 218.1],
      textContent: "水泥用灰岩",
      reserves: "3976.33万吨",
      index: 3,
    },
  ];
  endMid = 1410;
  constructor(map) {
    if (map) this.mapInstance = map;
    else throw new Error("constructor参数不能为空！");
    this.graphicLayer = new mars3d.layer.GraphicLayer();
    this.mapInstance.addLayer(this.graphicLayer);

    this.graphicLayer.enabledEvent = false; // 关闭事件，大数据addGraphic时影响加载时间
    this.mapInstance.on("click", (evt) => {
      // console.log("map-click-pickedObject", evt);
      let propertyID = evt.pickedObject?.tileset?.propertyID;
      if (propertyID === "layer" || propertyID === undefined) {
        const position = evt.cartesian;
        if (!evt.pickedObject?.content?.tile.extras) return;

        const layerInfo = evt.pickedObject.content.tile.extras.layerInfo;
        console.log("选中地层信息", layerInfo);
        // 是否显示拾取的地层名称
        if (this.showPickInfo) {
          let info = this.layersOptions.find(
            (item) => item.index === layerInfo.zoneIdx
          );
          let reserves = "-- 万吨";
          let html = `<div>地层：${layerInfo.name}</div>`;
          if (info) html += `<div>储量：${info.reserves}</div>`;
          map.openPopup(position, html);
        }
        // 可单个地层选中模式
        if (this.selectedLayerEnabled) {
          this.layerSelected(layerInfo.zoneIdx);
        }
      }
    });

    const { oreBodyId } = window.transparentEarthConfig;
    const viewer = map.viewer;
    this.viewer = viewer;
    // 保持分辨率尺度与显示器一致
    viewer.resolutionScale = window.devicePixelRatio;
    this.pointCollection = viewer.scene.primitives.add(
      new Cesium.PointPrimitiveCollection()
    );
    // this.loadModel(oreBodyId);
  }
  /**
   * 加载模型 终了模型 1410，现状模型1304
   */
  loadModel(mid) {
    console.log(mid, 'mid1111111111111111111');
    
    this.mid = mid;
    this.mapInstance.scene.globe.depthTestAgainstTerrain = false;
    if (this.gmodel) {
      this.clearEdit();
      this.gmodel.remove();
    }
    this.resetPoint();
    const url = `${window.transparentEarthConfig.serverAddress}/dev/3dtiles/package/tgmodel/Model_${mid}/Model_${mid}.json`;
    // console.log("url", url);
    const options = {
      mid,
      spaceID: this.spaceID,
      url,
      viewer: this.viewer,
      serverAddress:
        window.transparentEarthConfig.serverAddress ||
        "https://hz.gridworld.com.cn:50443/dev/",
      // serverAddress: "https://sz.gridworld.com.cn:10443/dev/",
    };
    GeologicalModel.fromUrl(options)
      .then((gmodel) => {
        this.gmodel = gmodel;
        console.log("gmodel", gmodel);
        // 飞行到模型位置
        gmodel.flyTo();
        // 默认隐藏
        // gmodel.switchShow(visible);
        // 默认不显示网格线
        gmodel.switchWireframe(false);
        // 抬升1米
        // this.gmodel.liftUp(0.1);

        console.log("toggleLayerShow", gmodel.toggleLayerShow);
        // gmodel.setAlpha(0.95);
        // //获取模型LOD网格信息
        gmodel.getModelGrid.then((gridList) => {
          console.log(gridList);
        });

        //获取模型属性信息
        gmodel.getModelProperty.then((options) => {
          console.log(options);
        });

        //获取模型地层色表信息
        gmodel.getModelLayerInfo.then((layerList) => {
          useReservesStore().setModelLayerList(layerList);
          console.log(layerList); // 地层
        });

        //获取模型属性色表信息
        gmodel.getModelColorChart.then((colorChart) => {
          console.log(colorChart);
        });
        // return;
        // 改变模型颜色
        setTimeout(() => {
          // 重新设置地层颜色
          const layerColors = {
            Ⅲ熔剂用白云岩矿: "#8F87FF",
            // 夹_8建筑用灰岩矿: "#00B7B7",
            // 夹_Ⅰ电石用石灰岩矿_1: "#FF88FF",
            Ⅰ电石用石灰岩矿: "#FF88FF",
            // 夹_1建筑用灰岩矿: "#00B7B7",
            "3建筑用灰岩矿": "#00B7B7",
            B2熔剂用白云岩矿: "#8F87FF",
            "4建筑用灰岩矿": "#00B7B7",
            B3熔剂用白云岩矿: "#8F87FF",
            // 夹_Ⅱ电石用石灰岩矿_6: "#FF88FF",
            // 夹_6建筑用灰岩矿: "#8F87FF",
            // 夹_Ⅱ电石用石灰岩矿_7: "#00B7B7",
            // 夹_7建筑用灰岩矿: "#FF88FF",
            Ⅱ电石用石灰岩矿: "#FF88FF",
            S1g: "#878787",
            残坡积层: "#5c5b5bff",
            Ⅳ: "#00B7B7",
            "①水泥用灰岩矿": "#B2FEF1",
            // 夹_2建筑用灰岩矿: "#00B7B7",
            // 夹_Ⅰ电石用石灰岩矿_2: "#FF88FF",
            // 夹_3建筑用灰岩矿_B1_2: "#00B7B7",
            // 夹_10建筑用灰岩矿: "#00B7B7",
            // 夹_Ⅰ电石用石灰岩矿_10: "#FF88FF",
            // 夹_3建筑用灰岩矿_B1_2: "#00B7B7",
            // 夹_B1熔剂用白云岩矿_1: "#8F87FF",
            // 夹_3建筑用灰岩矿_B1_1: "#00B7B7",
            // 夹_B1熔剂用白云岩矿: "#8F87FF",
            // 夹_5建筑用灰岩矿: "#00B7B7",
          };
          Object.keys(layerColors).forEach((key, index) => {
            setTimeout(() => {
              this.gmodel.setLayerColor(key, layerColors[key]);
            }, 1000 * index);
          });
        }, 1000 * 3);
      })
      .catch((err) => {
        console.log("GeologicalModel Error", err);
      });
  }
  /**
   * 移除地质模型,释放资源
   */
  removeModel() {
    if (this.gmodel) {
      this.clearEdit();
      this.gmodel.remove();
      this.removeSection();
    }
  }

  flytoModel() {
    this.gmodel.flyTo();
  }

  modelSetup(command, value) {
    switch (command) {
      case "lifting":
        this.liftUpVal = value;
        this.gmodel.liftUp(value);
        this.updateLabelheight();
        break;
      case "explosion":
        this.gmodel.explode(value);
        break;
      case "scale":
        this.gmodel?.scale(value);
        break;
      case "wireframe":
        this.gmodel.switchWireframe(value);
        break;
      case "draw-point":
        this.selectPoints();
        break;
      case "burrow":
        this.startClipping();
        break;
      case "clear-burrow":
        this.removeClipping();
        break;
      case "section":
        this.startSection();
        break;
      case "remove-section":
        this.removeSection();
        break;
      case "section-liftup":
        this.sectionLiftup(value);
        break;
      case "start-drilling":
        this.startDrilling();
        break;
      case "showLayer":
        this.switchLayerShow(value);
        break;
      case "showAlt":
        this.switchAltDisplayShow(value);
        break;
      case "showMark":
        this.showMarkLabel(value);
        break;
      case "propertyQuery":
        this.showPickInfo = value;
        break;
      case "layerSelected":
        this.selectedLayerEnabled = value;
        this.layerSelectedFlag = false;
        if (!value) {
          this.switchLayerShow([]);
          this.gmodel.liftUp(0.1);
          this.liftUpVal = 0;
        }
        break;
      // 开采计划
      case "designPlan":
        this.startDesign(value);
        break;
      // 输入绘制
      case "inputSection":
        this.inputSection(value);
        break;
      case "load-model":
        this.loadModel(value);
        break;
      default:
        break;
    }
  }

  /**
   * 地层开关
   * @param {*} value
   */
  switchLayerShow(layerArray) {
    this.gmodel.switchLayerShow(layerArray);
    this.updateVisibleByLayer(layerArray);
  }
  initModel() {
    const { oreBodyId } = window.transparentEarthConfig;
    this.loadModel(oreBodyId);
  }
  /**
   * 清楚编辑状态
   */
  clearEdit() {
    this.gmodel.explode(0);
    this.gmodel.scale(1);
    this.gmodel.switchWireframe(false);
    this.gmodel.liftUp(0.1);
    this.liftUpVal = 0;
    this.resetPoint();
    this.removeSection();
    this.removeClipping();
    this.switchLayerShow([]);
    // this.showMarkLabel(false);
    this.drill && this.drill.destroy();
    this.resetInput();
    this.showPickInfo = false;
    this.graphicLayer.clear(true);
    this.switchAltDisplayShow(false);
    this.selectedLayer = false;
    this.layerSelectedFlag = false;

    // this.gmodel.setAlpha(0.85);
    // setTimeout(() => {
    //   this.gmodel.showPropertyColor("地层");
    // }, 500);
  }
  /**
   * 传入两个坐标进行剖面操作
   * @param {*} positions
   */
  inputSection(positions) {
    this.resetInput();

    positions.forEach((tem) => {
      const cartesian3 = Cesium.Cartesian3.fromDegrees(tem.x, tem.y);
      this.pointCoordinationArray.push(cartesian3);
      // this.createPoint(cartesian3);
      // this.drawShape();
    });

    this.startSection();
  }
  /**
   * 单个地层选中
   */
  layerSelected(index) {
    // debugger
    this.layerSelectedFlag = !this.layerSelectedFlag;
    if (this.layerSelectedFlag) {
      this.liftUpVal = 250;
      // this.showMarkLabel(true);
      this.switchLayerShow([index]);
      this.gmodel.liftUp(250);

      // setTimeout(() => {}, 1000);
    } else {
      this.switchLayerShow([]);
      this.gmodel.liftUp(0.1);
      // this.showMarkLabel(false);
    }
  }
  /**
   * 清除选点事件
   */
  resetInput() {
    if (this.handler) {
      this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    this.resetPoint();
  }

  /**
   * 更新标注高度
   */
  updateLabelEntities() {
    if (!this.showMark) return;
    const { model } = this.gmodel;
    if (model.show) {
      for (let i = 0; i < this.labelEntities.length; i++) {
        this.labelEntities[i].show =
          model.layerShowArray.length == 0 ||
          model.layerShowArray.includes(this.labelLayerIds[i]);
        this.labelEntities[i].modelMatrix = Cesium.Matrix4.multiply(
          model.modelMatrix,
          this.labelRawMatrices[i],
          new Cesium.Matrix4()
        );
        this.labelEntities[i].refresh();
      }
    } else {
      for (let i = 0; i < this.labelEntities.length; i++) {
        this.labelEntities[i].show = false;
      }
    }
  }

  /**
   * 是否 网格中心点Z值 上色
   * @param {*} flag
   */
  switchAltDisplayShow(flag) {
    if (flag) {
      this.gmodel.showPropertyColor("网格中心点Z值");
    } else {
      this.gmodel.showPropertyColor("地层");
    }
  }
  /**
   * 根据图层显隐
   * @param {*} layerIndexArray
   */
  updateVisibleByLayer(layerIndexArray) {
    if (this.graphicLayer.show) {
      const graphics = this.graphicLayer.getGraphics();
      if (layerIndexArray.length > 0)
        graphics.forEach((graphic) => {
          graphic.show = layerIndexArray.includes(graphic.id);
        });
    }
  }
  /**
   * 加载label标注
   */
  loadLabels() {
    this.layersOptions.forEach((op) => {
      const graphic = new mars3d.graphic.DivGraphic({
        id: op.index,
        position: op.position,
        attr: { name: op.textContent, position: op.position },

        style: {
          html: `<div class="marsBlueGradientPnl">
              <div>${op.textContent}</div>
              <div>矿石量：${op.reserves}</div>
          </div>`,
          offsetY: -60,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,

          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0,
            5000
          ), // 按视距距离显示
        },

        // style: {
        //   html: `<div class="marsBlackPanel  animation-spaceInDown">
        //           <div class="marsBlackPanel-text">${op.textContent}<br> 矿石量：${op.reserves}</div>
        //           </div>`,
        //   scaleByDistance: true,
        //   scaleByDistance_far: 10000,
        //   scaleByDistance_farValue: 0.5,
        //   scaleByDistance_near: 500,
        //   scaleByDistance_nearValue: 1,
        //   horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
        //   verticalOrigin: Cesium.VerticalOrigin.CENTER,
        //   distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
        //     0,
        //     10000
        //   ), // 按视距距离显示
        //   // 高亮时的样式
        //   highlight: {
        //     // type: mars3d.EventType.click,
        //     className: "marsBlackPanel-highlight",
        //   },
        // },
      });
      this.graphicLayer.addGraphic(graphic);
    });
  }

  updateLabelheight() {
    if (this.graphicLayer.show) {
      const graphics = this.graphicLayer.getGraphics();
      graphics.forEach((graphic) => {
        const position = cloneDeep(graphic.options.attr.position);
        position[2] = position[2] + this.liftUpVal;
        graphic.position = position;
      });
    }
  }

  /**
   * 是否显示标注
   */
  async showMarkLabel(flag) {
    let graphics = this.graphicLayer.getGraphics();
    if (flag) {
      if (graphics.length) {
        this.graphicLayer.show = true;
      } else {
        this.loadLabels();
      }

      this.updateLabelheight();
    } else {
      if (graphics.length) {
        this.graphicLayer.show = false;
      }
    }

    // this.showMark = flag;
    // if (flag && this.labelEntities.length === 0) {
    //   // this.labelLayerIds = [10, 9, 8, 7, 6, 5, 4, 3];
    //   // setTimeout(() => {
    //   //   this.updateLabelEntities();
    //   // }, 800);
    // } else {
    //   for (let e of this.labelEntities) {
    //     e.show = flag;
    //   }
    // }
  }

  /**
   * 开采计划
   * @param {*} params 开采计划参数
   */
  startDesign(params) {
    const { stepAngle, stepHeight, plateWidth, polygon } = params;
    let data = {};
    data.polygon = polygon;
    data.model_hbase_id = `${this.mid}`;
    data.top_elevation = 265; // 顶点高程暂时写死
    data.bottom_elevation = 190; //65; // 最低开采标高
    data.stair_height = Number(stepHeight);
    data.stair_width = Number(plateWidth);
    data.stair_angle_deg = Number(stepAngle);
    $modal.loading("请稍后...");
    this.gmodel.getModelGrid.then((gridList) => {
      data.grid_id = `${gridList[gridList.length - 1]}`;
      drillApi
        .getTriangulation(data)
        .then((res) => {
          if (res.status == "success") {
            let tin = res.data.triangulation;

            let triangles = [];
            for (let tri of tin) {
              for (let pt of tri) {
                let ptCar3 = Cesium.Cartesian3.fromDegrees(...pt);
                triangles.push(ptCar3);
              }
            }

            this.gmodel.clip({
              triangles: triangles,
            });
            $modal.msgSuccess("计算成功！请耐心等待渲染完成！");

            // 去掉网格
            this.gmodel.switchWireframe(true);
            setTimeout(() => {
              this.gmodel.switchWireframe(false);
            }, 1000 * 3);
            // setTimeout(() => {
            //   $modal.loading("正在渲染，请稍后...");
            // }, 800);
            // setTimeout(() => {
            //   $modal.closeLoading();
            // }, 1000 * 8);
            // 清空选点事件
            // this.resetInput();
          }
        })
        .catch((err) => {
          $modal.msgWarning("设计参数不合理，无法生成三角网，请调整设计参数");
        })
        .finally(() => {
          setTimeout(() => {
            $modal.closeLoading();
          }, 1000 * 3.5);
        });
    });
  }

  /**
   * 选点
   */
  selectPoints() {
    let { viewer } = this;
    this.pointPrimitiveArray = [];
    this.pointCoordinationArray = [];
    this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    this.handler.setInputAction((event) => {
      if (
        viewer.scene.mode !== Cesium.SceneMode.MORPHING &&
        viewer.scene.pickPositionSupported
      ) {
        console.log(event.position,'event.positionevent.position');
        
        var earthPosition = viewer.scene.pickPosition(event.position);
        if (earthPosition === undefined) {
          return;
        }
        this.pointCoordinationArray.push(earthPosition);
        this.createPoint(earthPosition);
        this.drawShape();
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }

  /**
   * 开始分析
   */
  async startStatistics(points) {
    let type = 'polygon'
    // 执行统计
    let positions = points || this.pointCoordinationArray; // 统计区域位置集：circle-positions[0]: 圆心，positions[1]: 圆弧上一点；polygon-多边形位置集
    console.log(positions,'positionspositionspositions');
    
    let top = 1000; // 顶面高程， 暂不起作用
    let bottom = -1000; // 顶面高程，暂不起作用
    const model = this.gmodel;
    let res = await model.statistics(type, positions, top, bottom);
    
    console.log(this.pointCoordinationArray,'pointCoordinationArraypointCoordinationArray');
    
    console.log(res);

    // this.resetPoint();
    
    return res
    // 结构信息
    const tableBody1 = document.getElementById('structureTable').getElementsByTagName('tbody')[0];
    tableBody1.innerHTML = '';
    res.layerData.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.name}</td>
            <td>${item.volume}</td>
            <td>${item.volProp}</td>
            <td>${item.thickness}</td>
            <td>${item.faultNum}</td>
        `;
        tableBody1.appendChild(row);
    });
    // 连续属性信息
    const tableBody2 = document.getElementById('continuousTable').getElementsByTagName('tbody')[0];
    tableBody2.innerHTML = '';

    res.continuousPropData.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.name}</td>
            <td>${item.value_max}</td>
            <td>${item.value_min}</td>
        `;
        tableBody2.appendChild(row);
    });

    const select = document.getElementById('discreteSelect');
    select.innerHTML = '';

    res.discretePropNameList.forEach(item => {
        const option = document.createElement('option');
        option.value = item.name;
        option.textContent = item.name;
        select.appendChild(option);
    });
   // 离散属性信息
   this.disProp=res.disProp
    const tableBody3 = document.getElementById('discreteTable').getElementsByTagName('tbody')[0];
    tableBody3.innerHTML = '';
    res.discretePropData.forEach(item => {
      const row = document.createElement('tr');
      row.innerHTML = `
            <td>${item.name}</td>
            <td>${item.volume}</td>
            <td>${item.volProp}</td>
    `;
    tableBody3.appendChild(row);
    
  })
  handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    resetPoint()
  }

  createPoint(worldPosition) {
    if (worldPosition === undefined) {
      return;
    }

    let point = {
      position: new Cesium.Cartesian3(
        worldPosition.x,
        worldPosition.y,
        worldPosition.z
      ),
      color: Cesium.Color.RED,
    };

    let p = this.pointCollection.add(point);
    this.pointPrimitiveArray.push(p);
    return point;
  }
  /**
   * 挖洞
   */
  startClipping() {
    const { pointCoordinationArray } = this;
    if (pointCoordinationArray.length > 2) {
      this.gmodel.clip({
        points: pointCoordinationArray,
      });
      this.gmodel.switchWireframe(true);
      setTimeout(() => {
        this.gmodel.switchWireframe(false);
      }, 500);
      // this.resetPoint();
      this.resetInput();
    } else {
      $modal.msgWarning("请选点！");
    }
  }
  /**
   * 清空挖洞
   */
  removeClipping() {
    this.gmodel.removeClipping();
    this.resetInput();
  }
  /**
   * 模型剖切
   */
  startSection() {
    // console.log("剖面源坐标", this.pointCoordinationArray);
    if (this.pointCoordinationArray.length > 0) {
      $modal.loading("请稍后...");
      this.gmodel
        .addSection({
          points: this.pointCoordinationArray,
        })
        .then((section) => {
          this.section = section;
          // 默认不显示剖面网格
          this.section.switchWireframe(false);
          // 默认抬升25m
          this.section.liftUp(25);
          // 剖面上色与模型保持一致
          this.section.coloringWithModel(this.gmodel);
          setTimeout(() => {
            this.section.showLabel(false);
          }, 1000 * 10);

          // 网格线与模型保持一致
          this.section.switchWireframe(this.gmodel.model.showWireFrame);
          $modal.msgSuccess("生成剖面成功！");
          this.resetInput();
        })
        .finally(() => {
          $modal.closeLoading();
        });
    } else {
      $modal.msgWarning("请选点！");
    }
  }

  /**
   * 剖切抬升
   * @param {*} value
   */
  sectionLiftup(value) {
    if (this.section) {
      this.section.liftUp(value);
    }
  }

  /**
   * 移除剖切
   */
  removeSection() {
    if (this.section) {
      this.section.remove();
      this.section = undefined;
      this.resetInput();
    }
  }
  /**
   * 生成钻孔
   */
  startDrilling() {
    const { pointCoordinationArray } = this;
    if (pointCoordinationArray.length > 0) {
      this.gmodel
        .createVirtualDrill(this.pointCoordinationArray)
        .then((drill) => {
          if (drill) {
            let drillId = drill.id;
            console.log(drillId);
            this.drill = drill;
            // 更新钻孔的显示：包含大部分钻孔的接口使用案例
            this.updateDrill(drill);
            $modal.msgSuccess("生成钻孔成功！");
          }
        })
        .catch((err) => {
          $modal.msgError("生成钻孔失败！");
        })
        .finally(() => {
          this.resetPoint();
        });
    } else {
      $modal.msgWarning("请选点！");
    }
  }


  /**
   * 清空绘制结果
   */
  resetPoint() {
    for (var i = this.pointPrimitiveArray.length - 1; i >= 0; i--) {
      this.pointCollection.remove(this.pointPrimitiveArray[i]);
    }
    this.pointPrimitiveArray = [];
    this.pointCoordinationArray = [];
    if (this.polygonPrimitive != null) {
      this.viewer.scene.primitives.removeAndDestroy(this.polygonPrimitive);
      this.polygonPrimitive = null;
    }
  }

  drawShape() {
    // console.log({ pointCoordinationArray });
    if (this.pointCoordinationArray.length < 3) return;
    //计算凸包，阻止用户勾选凹多边形
    this.pointCoordinationArray = this.convexHull(
      this.pointCoordinationArray.slice(0)
    ).slice(0);

    var pointCollection = this.pointCoordinationArray.slice(0);
    pointCollection.push(this.pointCoordinationArray[0]);
    this.drawPolygon(pointCollection);
  }

  drawPolygon(points) {
    let { viewer } = this;
    if (this.polygonPrimitive != null) {
      viewer.scene.primitives.removeAndDestroy(this.polygonPrimitive);
      this.polygonPrimitive = null;
    }
    this.polygonPrimitive = new Cesium.Primitive({
      geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.PolylineGeometry({
          positions: points,
          width: 2.0,
          vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
        }),
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(
            Cesium.Color.CORAL
          ),
        },
      }),
      appearance: new Cesium.PolylineColorAppearance({
        translucent: false,
        closed: false,
        renderState: {
          depthTest: {
            enabled: false,
          },
          depthMask: false,
        },
      }),
      asynchronous: false,
    });
    viewer.scene.primitives.add(this.polygonPrimitive);
  }

  convexHull(points) {
    points.sort(function (a, b) {
      return a.x != b.x ? a.x - b.x : a.y - b.y;
    });
    var n = points.length;
    var hull = [];
    for (var i = 0; i < 2 * n; i++) {
      var j = i < n ? i : 2 * n - 1 - i;
      while (
        hull.length >= 2 &&
        this.removeMiddle(
          hull[hull.length - 2],
          hull[hull.length - 1],
          points[j]
        )
      )
        hull.pop();
      hull.push(points[j]);
    }
    hull.pop();
    return hull;
  }

  removeMiddle(a, b, c) {
    var cross = (a.x - b.x) * (c.y - b.y) - (a.y - b.y) * (c.x - b.x);
    var dot = (a.x - b.x) * (c.x - b.x) + (a.y - b.y) * (c.y - b.y);
    return cross < 0 || (cross == 0 && dot <= 0);
  }

  updateDrill(drill) {
    if (drill) {
      // 视角飞到钻孔
      drill.flyTo();

      // 隐藏钻孔
      // drill.toggleSetShow(false);

      // 显示钻孔
      // drill.toggleSetShow(true);

      // 隐藏钻孔名称
      // drill.toggleNameSetShow(false);

      // 显示钻孔名称
      // drill.toggleNameSetShow(true);

      // 修改名称大小
      // drill.updateNameSize(20);

      // 修改名称颜色
      // drill.updateNameColor("rgba(255,0,0,1)");

      // 隐藏孔位点
      // drill.togglePositionSetShow(false);

      // 显示孔位点
      // drill.togglePositionSetShow(true);

      // 隐藏孔位点
      // drill.togglePositionSetShow(true);

      // 修改孔位大小
      // drill.updatePositionSize(10);

      // 修改孔位颜色
      // drill.updatePositionColor("rgba(255,255,255,1)");

      // 隐藏钻孔轨迹
      // drill.toggleTrajectorySetShow(false);

      // 显示钻孔轨迹
      // drill.toggleTrajectorySetShow(true);

      // 修改钻孔轨迹宽度
      // drill.updateTrajectoryWidth(10);

      // 修改钻孔轨迹颜色
      // drill.updateTrajectoryColor("rgba(255,255,255,1)");

      // 隐藏分层
      // drill.toggleLayerShow(false);

      // 显示分层
      // drill.toggleLayerShow(true);

      // 隐藏指定分层
      // drill.toggleLayerShow(false, 'Q4');

      // 显示指定分层
      // drill.toggleLayerShow(true, 'Q4');

      // 切换分层类型为圆片
      // drill.toggleLayerType('circle');

      // 切换分层类型为圆柱
      // drill.toggleLayerType('cylinder');

      // 修改分层圆柱或圆片的半径
      // drill.updatePropertyRadius(20);

      // 修改分层颜色
      // let propName = 'layer';
      // let drillLayerColorMap = new Map([['Q4', 'rgba(255,0,0,1)'], ['滑带土', 'rgba(0,255,0,1)'], ['T2b', 'rgba(0,0,255,1)']]);
      // drill.updatePropertyColorMap(propName, drillLayerColorMap);

      // 销毁钻孔图元
      // drill.destroy();
    }
  }
}

export default modelEditor;
